package com.jack.blog.utils;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.sql.Timestamp;
import java.util.Properties;

public final class MessageUtil {

    private static final String host="smtp.qq.com";
    private static final int port=25;
    private static final String protocol="smtp";
    private static String mail="1178733235@qq.com";
    private static String subject="来自南山扛把子的回复!";
    private static String username="1178733235@qq.com";
    private static String password="xhuopkgtqgalicfd";
    private static String contentType="text/plain;charset=UTF-8";

    public static void setUsername(String userName){
        mail=username;
        username=userName;
    }

    public static void setPassword(String pwd){
        password=pwd;
    }

    public static void sendMail(String content, String toEmail, Timestamp replyTime) throws Exception {

        Properties props = new Properties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.auth", true);
        props.put("mail.transport.protocol", protocol);
        props.put("mail.smtp.port", port);
        props.put("mail.debug", true);

        Session mailSession = Session.getDefaultInstance(props);
        MimeMessage message = new MimeMessage(mailSession);
        message.setSubject(subject);
        message.setContent(content, contentType);
        message.setSentDate(replyTime);
        message.setFrom(new InternetAddress(mail));
        message.setRecipient(Message.RecipientType.TO,new InternetAddress(toEmail));
        Transport transport = mailSession.getTransport();
        message.saveChanges();

        transport.connect(host, username, password);
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
    }
}
